package com.apanal.qlife.sys.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.page.Page;
import com.apanal.qlife.common.page.PageReturn;
import com.apanal.qlife.common.util.IdWorkerFactory;
import com.apanal.qlife.sys.dao.SysLogMapper;
import com.apanal.qlife.sys.model.SysLog;
import com.apanal.qlife.sys.service.SysLogService;

/**
 * 系统操作日志服务层接口实现类
 * 
 * @author shuliangxing
 * 
 * @date 2015-1-14上午11:36:08
 */
@Service
public class SysLogServiceImpl implements SysLogService {

	@Autowired
	SysLogMapper mapper;

	@Override
	public String deleteById(Long id) {
		mapper.deleteByPrimaryKey(id);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String insert(SysLog record) {
		if (record.getLogId() == null) {
			record.setLogId(IdWorkerFactory.nextId());
		}
		mapper.insert(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String insertSelective(SysLog record) {
		mapper.insertSelective(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public SysLog selectById(Long id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public String updateByIdSelective(SysLog record) {
		mapper.updateByPrimaryKeySelective(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public String updateById(SysLog record) {
		mapper.updateByPrimaryKey(record);
		return Constants.DEFAULT_MSG_SUCCESS;
	}

	@Override
	public PageReturn<SysLog> selectRelationForPage(SysLog entity, Page page) {
		// useId=0为匿名用户
		if (entity.getInsertName() != null
				&& Constants.ANONYMOUS_USER.equals(entity.getInsertName()
						.trim())) {
			entity.setInsertName(null);
			entity.setUseId(0l);
		}

		int count = mapper.selectRelationForPageCount(entity, page);
		List<SysLog> list = mapper.selectRelationForPage(entity, page);

		for (SysLog sysLog : list) {
			if (sysLog.getUseId() == 0) {
				sysLog.setInsertName(Constants.ANONYMOUS_USER);
			}
		}

		if (entity.getUseId() != null && entity.getUseId() == 0) {
			entity.setInsertName(Constants.ANONYMOUS_USER);
			entity.setUseId(null);
		}
		return new PageReturn<SysLog>(list, count, page, entity);
	}

}
